﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using ReportMealManagementSystem.Business;
using ReportMealManagementSystem.Entity;
using ReportMealManagementSystem.Tool;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Configuration;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace ReportMealManagementSystem
{
    /// <summary>
    /// DishesClassSetting.xaml 的交互逻辑
    /// </summary>
    public partial class DishesClassSetting : UserControl
    {
        Configuration cfa = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        int districtID = int.Parse(ConfigurationManager.AppSettings["districtID"]);
        BasicInfo basicInfo = new BasicInfo();
        int pageIndex = 1;
        int pageSize = 50;
        int totalNumber = 0;
        int totalPage = 0;
        ObservableCollection<object> observableCollection = null;
        State state = State.None;
        JObject joItem = new JObject();
        JObject joParam = new JObject();
        ValueVerify valueVerify = new ValueVerify();

        public DishesClassSetting()
        {
            InitializeComponent();
        }

        private void GetDishesClassInfo()
        {
            string msg = "";
            var DistrictList = basicInfo.GetData(joParam, "gbt/BasicInfo/DishesClassInfo", "菜品分类", ref totalNumber, ref totalPage, ref msg);
            if (DistrictList != null)
            {
                JObject joItem = new JObject();
                observableCollection = new ObservableCollection<object>();
                for (int index = 0; index < DistrictList.Count; index++)
                {
                    joItem = (JObject)DistrictList[index];
                    observableCollection.Add(new
                    {
                        ID = (int)joItem["id"],
                        HallID = (int)joItem["hallID"],
                        Number = (string)joItem["number"],
                        Name = (string)joItem["name"],
                        qty = (string)joItem["qty"],
                        HallNumber = (string)joItem["hallNumber"],
                        HallName = (string)joItem["hallName"],
                        DistrictID = (string)joItem["districtID"],
                        DistrictNumber = (string)joItem["districtNumber"],
                        DistrictName = (string)joItem["districtName"],
                    });
                }

                lvDate.Dispatcher.Invoke(new Action(delegate
                {
                    lvDate.ItemsSource = observableCollection;
                    message.Content = msg;
                }));
            }
        }

        private void GetDiningHallInfo()
        {
            string msg = "";
            JObject joDiningHallParam = new JObject();
            joDiningHallParam["PageIndex"] = 1;
            joDiningHallParam["PageSize"] = 1000;
            joDiningHallParam["DistrictID"] = districtID;
            int totalNumber = 0;
            int totalPage = 0;
            var DistrictList = basicInfo.GetData(joDiningHallParam, "gbt/BasicInfo/DiningHallInfo/", "食堂", ref totalNumber, ref totalPage, ref msg);
            if (DistrictList != null)
            {
                JObject joItem = new JObject();
                List<SelectedItem> selectedItems = new List<SelectedItem>();
                selectedItems.Add(new SelectedItem
                {
                    ID = null,
                    Name = ""
                });
                for (int index = 0; index < DistrictList.Count; index++)
                {
                    joItem = (JObject)DistrictList[index];
                    selectedItems.Add(new SelectedItem
                    {
                        ID = (int)DistrictList[index]["hallId"],
                        Name = (string)DistrictList[index]["hallName"]
                    });
                }

                cbHallName.Dispatcher.Invoke(new Action(delegate
                {
                    cbHallName.ItemsSource = selectedItems;
                    cbHallName.SelectedIndex = 0;
                }));
            }
        }

        private void GetDistrictInfo()
        {
            string msg = "";
            JObject joCompanyParam = new JObject();
            joCompanyParam["PageIndex"] = 1;
            joCompanyParam["PageSize"] = 1000;
            joCompanyParam["DistrictID"] = districtID;
            int totalNumber = 0;
            int totalPage = 0;
            var DistrictList = basicInfo.GetData(joCompanyParam, "gbt/BasicInfo/DistrictList/", "区域", ref totalNumber, ref totalPage, ref msg);
            if (DistrictList != null)
            {
                JObject joItem = new JObject();
                List<SelectedItem> selectedItems = new List<SelectedItem>();
                for (int index = 0; index < DistrictList.Count; index++)
                {
                    joItem = (JObject)DistrictList[index];
                    selectedItems.Add(new SelectedItem
                    {
                        ID = (int)DistrictList[index]["districtID"],
                        Name = (string)DistrictList[index]["districtName"]
                    });
                }

                cbName.Dispatcher.Invoke(new Action(delegate
                {
                    cbName.ItemsSource = selectedItems;
                    cbName.SelectedIndex = 0;
                }));
            }
        }

        private void OptDishesClassInfo(string optState)
        {
            _loading.Visibility = Visibility.Visible;
            bData.Visibility = Visibility.Collapsed;
            string message = "";
            Task task = new Task(new Action(delegate
            {
                JObject joParam = new JObject();
                wpData.Dispatcher.Invoke(new Action(delegate
                {
                    if (this.state == State.Modify || this.state == State.Delete)
                    {
                        if (lvDate.SelectedItem == null)
                        {
                            sbStart.Dispatcher.Invoke(new Action(delegate
                            {
                                this.message.Content = "请选择行";
                            }));
                            return;
                        }
                        joParam["id"] = joItem["ID"];
                    }
                    joParam["number"] = txtNumber.Text.Trim();
                    joParam["name"] = txtName.Text.Trim();
                    if (cbName.SelectedValue != null)
                    {
                        joParam["districtID"] = (int)cbName.SelectedValue;
                    }
                    if (cbHallName.SelectedValue != null)
                    {
                        joParam["hallID"] = (int)cbHallName.SelectedValue;
                    }
                    joParam["qty"] = txtQty.Text.Trim();
                    joParam["state"] = optState;
                }));
                this.state = State.Save;
                var state = basicInfo.OptDataInfo(joParam, "gbt/BasicInfo/OptDishesClass/", ref message);

                this.txtPageIndex.Dispatcher.Invoke(new Action(delegate
                {
                    txtPageIndex.Text = "1";
                }));
                pageIndex = 1;
                joParam = new JObject();
                joParam["PageIndex"] = pageIndex;
                joParam["PageSize"] = pageSize;
                joParam["DistrictID"] = districtID;
                GetDishesClassInfo();
            }));
            task.Start();
            task.ContinueWith((t) =>
            {
                _loading.Dispatcher.Invoke(new Action(delegate
                {
                    state = State.None;
                    txtNumber.Text = "";
                    txtName.Text = "";
                    cbName.SelectedValue = null;
                    lvDate.IsEnabled = true;
                    this.message.Content = message;
                    _loading.Visibility = Visibility.Collapsed;
                }));
            });
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            _loading.Visibility = Visibility.Visible;
            txtPageIndex.Text = "1";
            Task task = new Task(new Action(delegate
            {
                pageIndex = 1;
                joParam["PageIndex"] = pageIndex;
                joParam["PageSize"] = pageSize;
                joParam["DistrictID"] = districtID;
                GetDiningHallInfo();
                GetDishesClassInfo();
                GetDistrictInfo();
            }));
            task.Start();
            task.ContinueWith((t) =>
            {
                _loading.Dispatcher.Invoke(new Action(delegate
                {
                    _loading.Visibility = Visibility.Collapsed;
                }));
            });
        }

        private void Search_Click(object sender, RoutedEventArgs e)
        {
            if (state == State.None)
            {
                bData.Visibility = Visibility.Visible;
                bData.Height = 340;
                wpData.Height = 340;
                lvDate.IsEnabled = false;
                state = State.Search;
                lblTitle.Content = "查询";
            }
            else if (state == State.Search)
            {
                _loading.Visibility = Visibility.Visible;
                bData.Visibility = Visibility.Collapsed;
                bData.Height = 340;
                wpData.Height = 340;
                lvDate.IsEnabled = true;
                var attributeNumber = txtNumber.Text.Trim();
                var attributeName = txtName.Text.Trim();
                int hallID = 0;
                if (cbHallName.SelectedValue != null)
                {
                    hallID = (int)cbHallName.SelectedValue;
                }
                txtPageIndex.Text = "1";
                Task task = new Task(new Action(delegate
                {
                    pageIndex = 1;
                    joParam = new JObject();
                    joParam["PageIndex"] = pageIndex;
                    joParam["PageSize"] = pageSize;
                    joParam["Name"] = attributeName;
                    joParam["Number"] = attributeNumber;
                    if (hallID != 0)
                    {
                        joParam["HallID"] = hallID;
                    }
                    joParam["DistrictID"] = districtID;
                    GetDishesClassInfo();
                }));
                task.Start();
                task.ContinueWith((t) =>
                {
                    _loading.Dispatcher.Invoke(new Action(delegate
                    {
                        _loading.Visibility = Visibility.Collapsed;
                        lvDate.IsEnabled = true;
                    }));
                    state = State.None;
                });
            }
        }

        private void Add_Click(object sender, RoutedEventArgs e)
        {
            if (state != State.None)
            {
                return;
            }
            lblTitle.Content = "新增";
            bData.Visibility = Visibility.Visible;
            bData.Height = 320;
            wpData.Height = 320;
            state = State.Add;
            lvDate.IsEnabled = false;
            txtName.Text = "";
            txtNumber.Text = "";
            txtQty.Text = "";
            cbHallName.SelectedValue = null;
        }

        private void Modify_Click(object sender, RoutedEventArgs e)
        {
            if (state != State.None)
            {
                return;
            }

            if (lvDate.SelectedItem == null)
            {
                message.Content = "请选择行";
                return;
            }
            state = State.Modify;
            lvDate.IsEnabled = false;
            lblTitle.Content = "修改";
            bData.Visibility = Visibility.Visible;
            bData.Height = 320;
            wpData.Height = 320;
            joItem = new JObject();
            joItem = JObject.Parse(JsonConvert.SerializeObject(lvDate.SelectedItem));
            if (joItem != null)
            {
                txtNumber.Text = (string)joItem["Number"];
                txtName.Text = (string)joItem["Name"];
                txtQty.Text = (string)joItem["qty"];
                cbName.SelectedValue = (int)joItem["DistrictID"];
                cbHallName.SelectedValue = (int)joItem["HallID"];
            }
        }

        private void Save_Click(object sender, RoutedEventArgs e)
        {
            if (state == State.None || state == State.Search)
            {
                return;
            }

            string message = "";
            bool start = true;
            if (string.IsNullOrEmpty(txtNumber.Text.Trim()))
            {
                message += "通讯录编号不能为空" + Environment.NewLine;
                start = false;
            }
            if (string.IsNullOrEmpty(txtName.Text.Trim()))
            {
                message += "通讯录名称不能为空" + Environment.NewLine;
                start = false;
            }
            if (!valueVerify.IsNumber(txtQty.Text.Trim()))
            {
                message += "可选数量输入错误" + Environment.NewLine;
                start = false;
            }
            if (cbHallName.SelectedValue == null)
            {
                message += "食堂名称不能为空" + Environment.NewLine;
                start = false;
            }

            if (cbName.SelectedValue == null)
            {
                message += "区域名称不能为空" + Environment.NewLine;
                start = false;
            }

            if (!start)
            {
                MessageBox.Show(message, "温馨提示", MessageBoxButton.OK);
                return;
            }

            switch (state)
            {
                case State.Add:
                    OptDishesClassInfo("add");
                    break;
                case State.Modify:
                    OptDishesClassInfo("modify");
                    break;
            }
        }

        private void Delete_Click(object sender, RoutedEventArgs e)
        {
            if (lvDate.SelectedItem == null)
            {
                message.Content = "请选择行";
                return;
            }
            state = State.Delete;
            joItem = new JObject();
            joItem = JObject.Parse(JsonConvert.SerializeObject(lvDate.SelectedItem));
            MessageBoxResult messageBoxResult = MessageBox.Show("确认删除菜品分类 “" + (string)joItem["Name"] + "”", "温馨提醒", MessageBoxButton.YesNo);
            if (messageBoxResult == MessageBoxResult.Yes)
            {
                OptDishesClassInfo("del");
            }
            else
            {
                state = State.None;
            }
        }

        private void Cancel_Click(object sender, RoutedEventArgs e)
        {
            state = State.None;
            bData.Visibility = Visibility.Collapsed;
            bData.Height = 320;
            wpData.Height = 320;
            lvDate.IsEnabled = true;

            txtNumber.Text = "";
            txtName.Text = "";
            txtQty.Text = "";
            cbHallName.SelectedValue = null;
        }

        private void lvData_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (lvDate.SelectedItem != null)
            {
                state = State.Modify;
                lvDate.IsEnabled = false;
                lblTitle.Content = "修改";
                bData.Visibility = Visibility.Visible;
                bData.Height = 320;
                wpData.Height = 320;
                joItem = new JObject();
                joItem = JObject.Parse(JsonConvert.SerializeObject(lvDate.SelectedItem));
                if (joItem != null)
                {
                    txtNumber.Text = (string)joItem["Number"];
                    txtName.Text = (string)joItem["Name"];
                    txtQty.Text = (string)joItem["qty"];
                    cbName.SelectedValue = (int)joItem["DistrictID"];
                    cbHallName.SelectedValue = (int)joItem["HallID"];
                }
            }
        }

        private void BtnClose_Click(object sender, RoutedEventArgs e)
        {
            state = State.None;
            bData.Visibility = Visibility.Collapsed;
            bData.Height = 320;
            wpData.Height = 320;
            lvDate.IsEnabled = true;

            txtNumber.Text = "";
            txtName.Text = "";
            txtQty.Text = "";
            cbHallName.SelectedValue = null;
        }

        private void btnFirstPage_Click(object sender, RoutedEventArgs e)
        {
            _loading.Visibility = Visibility.Visible;
            txtPageIndex.Text = "1";
            Task task = new Task(new Action(delegate
            {
                pageIndex = 1;
                joParam["PageIndex"] = pageIndex;
                GetDishesClassInfo();
            }));
            task.Start();
            task.ContinueWith((t) =>
            {
                _loading.Dispatcher.Invoke(new Action(delegate
                {
                    _loading.Visibility = Visibility.Collapsed;
                }));
            });
        }

        private void btnPageUp_Click(object sender, RoutedEventArgs e)
        {
            _loading.Visibility = Visibility.Visible;
            Task task = new Task(new Action(delegate
            {
                if (pageIndex > 1)
                {
                    pageIndex--;
                    txtPageIndex.Dispatcher.Invoke(new Action(delegate
                    {
                        txtPageIndex.Text = pageIndex.ToString();
                    }));
                    joParam["PageIndex"] = pageIndex;
                    GetDishesClassInfo();
                }
            }));
            task.Start();
            task.ContinueWith((t) =>
            {
                _loading.Dispatcher.Invoke(new Action(delegate
                {
                    _loading.Visibility = Visibility.Collapsed;
                }));
            });
        }

        private void btnSkip_Click(object sender, RoutedEventArgs e)
        {
            _loading.Visibility = Visibility.Visible;
            if (!string.IsNullOrEmpty(txtPageIndex.Text.Trim()) && valueVerify.IsNumber(txtPageIndex.Text.Trim()))
            {
                pageIndex = int.Parse(txtPageIndex.Text.Trim());
                if (pageIndex == 0)
                {
                    pageIndex = 1;
                    txtPageIndex.Text = "1";
                }
                else if (pageIndex == totalPage)
                {
                    pageIndex = totalPage;
                    txtPageIndex.Text = totalPage.ToString();
                }
            }
            Task task = new Task(new Action(delegate
            {
                joParam["PageIndex"] = pageIndex;
                GetDishesClassInfo();
            }));
            task.Start();
            task.ContinueWith((t) =>
            {
                _loading.Dispatcher.Invoke(new Action(delegate
                {
                    _loading.Visibility = Visibility.Collapsed;
                }));
            });
        }

        private void btnNextPage_Click(object sender, RoutedEventArgs e)
        {
            _loading.Visibility = Visibility.Visible;
            Task task = new Task(new Action(delegate
            {
                if (pageIndex < totalPage)
                {
                    pageIndex++;
                    txtPageIndex.Dispatcher.Invoke(new Action(delegate
                    {
                        txtPageIndex.Text = pageIndex.ToString();
                    }));
                    joParam["PageIndex"] = pageIndex;
                    GetDishesClassInfo();
                }
            }));
            task.Start();
            task.ContinueWith((t) =>
            {
                _loading.Dispatcher.Invoke(new Action(delegate
                {
                    _loading.Visibility = Visibility.Collapsed;
                }));
            });
        }

        private void btnEndPage_Click(object sender, RoutedEventArgs e)
        {
            _loading.Visibility = Visibility.Visible;
            Task task = new Task(new Action(delegate
            {
                if (totalPage > 0)
                {
                    pageIndex = totalPage;
                }
                else
                {
                    pageIndex = 1;
                }
                txtPageIndex.Dispatcher.Invoke(new Action(delegate
                {
                    txtPageIndex.Text = pageIndex.ToString();
                }));
                joParam["PageIndex"] = pageIndex;
                GetDishesClassInfo();
            }));
            task.Start();
            task.ContinueWith((t) =>
            {
                _loading.Dispatcher.Invoke(new Action(delegate
                {
                    _loading.Visibility = Visibility.Collapsed;
                }));
            });
        }
    }
}
